package app

import (
	"fmt"
	"gin-web/app/core/config"
	"gin-web/app/core/db"
	"gin-web/app/core/log"
	redis2 "gin-web/app/core/redis"
	"github.com/go-redis/redis"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

var Config *config.Config

func Init(prjHome string) (err error) {
	configDef := prjHome + "/config/config-default.yml"
	configOverride := prjHome + "/config/config.yml"

	//读取配置文件
	Config = config.NewConfig()
	Config.PrjHome = prjHome + "/"
	err = Config.ParseConfig(configDef)
	if err != nil {
		return err
	}

	//重载配置
	err = Config.ParseConfig(configOverride)
	if err != nil {
		return err
	}

	//重载环境变量
	Config.MergeEnv()
	return
}

func DBW(keys ...string) *gorm.DB {
	k := "default"
	if len(keys) > 0 {
		k = keys[0]
	}

	dbConf, ok := Config.Db[k]
	if !ok {
		panic(fmt.Sprintf("db conf not found: %s", k))
	}

	cacheKey := fmt.Sprintf("%s_write", k)
	return db.Load(dbConf.Write, cacheKey)
}

func DBR(keys ...string) *gorm.DB {
	k := "default"
	if len(keys) > 0 {
		k = keys[0]
	}

	dbConf, ok := Config.Db[k]
	if !ok {
		panic(fmt.Sprintf("db conf not found: %s", k))
	}

	cacheKey := fmt.Sprintf("%s_read", k)
	return db.Load(dbConf.Read, cacheKey)
}

// Log 获取日志实例
func Log() *logrus.Entry {
	return log.LoadLog(Config.Log, Config.PrjHome)
}

func RedisR(key ...string) *redis.Client {
	k := "default"
	if len(key) > 0 {
		k = key[0]
	}

	cfg, ok := Config.Redis[k]
	if !ok {
		panic(fmt.Sprintf("db conf not found: %s", k))
	}

	cacheKey := fmt.Sprintf("%s_read", k)
	return redis2.Load(cfg.Read, cacheKey)
}

func RedisW(key ...string) *redis.Client {
	k := "default"
	if len(key) > 0 {
		k = key[0]
	}

	cfg, ok := Config.Redis[k]
	if !ok {
		panic(fmt.Sprintf("db conf not found: %s", k))
	}

	cacheKey := fmt.Sprintf("%s_read", k)
	return redis2.Load(cfg.Write, cacheKey)
}
